package kp.rpc;

import kp.rpc.config.RegistryConfig;
import kp.rpc.config.RpcConfig;
import kp.rpc.constants.RpcConstant;
import kp.rpc.registry.Registry;
import kp.rpc.registry.factory.RegistryFactory;
import kp.rpc.utils.ConfigUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * Hello world!
 */
@Slf4j
public class RpcApplication {
    private volatile static RpcConfig rpcConfig;

    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("rpc init,config={}", newRpcConfig.toString());
        //注册中心初始化
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getRegistry(registryConfig.getRegisterType());
        registry.init(registryConfig);
        log.info("registry init,config=>{}", registryConfig);
    }

    public static void init() {
        RpcConfig newRpcConfig;
        try {
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
        } catch (Exception e) {
            //如果加载失败!
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }


    /**
     * 懒汉加载模式
     */
    public static RpcConfig getRpcConfig() {
        if (rpcConfig == null) {
            synchronized (RpcApplication.class) {
                if (rpcConfig == null) {
                    init();
                }
                return rpcConfig;
            }
        }
        return rpcConfig;
    }
}
